#![allow(unused)]

use clap::Parser;
use std::io;

#[derive(Parser, Debug)]
struct Cli {
    pattern: String,
    path: std::path::PathBuf,
}

/*fn main() {
    // let pattern = std::env::args().nth(1).expect("no pattern given");
    // let path = std::env::args().nth(2).expect("no path given");

    //$ cargo run -- some-pattern some-file
    //     Finished dev [unoptimized + debuginfo] target(s) in 0.11s
    //      Running `target/debug/grrs some-pattern some-file`
    let args = Cli::parse();  //接受命令参数输入
    println!(">>>>命令参数内容：{:?}", args);

    //打开文本
    // let content = std::fs::read_to_string(&args.path).expect("读取文本文件失败");
    //逐行读取文件内容。读取文件内容到内存，如果是大文件，不可取。
    // for line in content.lines() {
    //     // println!(">>>>line = {}", line);
    //     if line.contains(&args.pattern) {
    //         println!(">>>>> pattern content: {}", line);
    //     }
    // }

    //更好方式
    //let result = std::fs::read_to_string(&args.path);
    /*match result {
        Ok(content) => {
            println!(">>>file content: {}", content);
        }
        Err(error) => {
            println!(">>>>read file error: {error}")
        }
    }*/
    /*let content = match result {
        Ok(content) => { content }
        Err(error) => { panic!("Can't deal with {}, just exit here", error); }
    };
    println!("读取的文件内容：{}", content);*/

    /*let content = std::fs::read_to_string(&args.path).unwrap();
    println!("file content: {}", content);*/
}*/

/*#[derive(Debug)]
struct CustomError(String); //自定义错误类型
fn main() -> Result<(), CustomError> {
    let args = Cli::parse();
    let content = std::fs::read_to_string(&args.path)
        .map_err(|err| CustomError(format!("Error reading `{:?}`: {}", &args.path, err)))?;
    println!("file content: {}", content);
    Ok(())
}*/

use anyhow::{Context, Result};
fn main() -> Result<()> {
    let args = Cli::parse(); //接受命令参数输入
    println!(">>>>命令参数内容：{:?}", args);
    let content = std::fs::read_to_string(&args.path)
        .with_context(|| format!("could not read file `{:?}`", &args.path))?;
    println!("file content: {}", content);

    // let stdout = io::stdout(); //get the global stdout entity
    // let mut handle = stdout.lock(); //acquire a lock on it
    // writeln!(handle, "{}", content);

    Ok(())
}
